package com.mj.single;

import com.mj.AbstractList;

/**
 * 添加虚拟头节点
 *
 * @param <E>
 */
public class SingleLinkedList2<E> extends AbstractList<E> {

    private Node<E> first;

    //不管有没有数据 都需要一个虚拟头节点
    public SingleLinkedList2() {
        first = new Node<>(null, null);
    }


    private static class Node<E> {
        E element;
        Node<E> next;

        public Node(E element, Node<E> next) {
            this.element = element;
            this.next = next;
        }
    }

    @Override
    public void clear() {
        size = 0;
        first = null;
    }

    /**
     * 获取节点中的数据
     *
     * @param index
     * @return
     */
    @Override
    public E get(int index) {

        return getNode(index).element;
    }

    /**
     * 先把之前的元素取出来,在覆盖
     *
     * @param index
     * @param element
     * @return
     */
    @Override
    public E set(int index, E element) {
        Node<E> oldNode = getNode(index);
        E oldElement = oldNode.element;
        oldNode.element = element;
        return oldElement;
    }

    @Override
    public void add(int index, E element) {
        rangeCheckForAdd(index);
        //统一处理
        Node<E> pre = index == 0 ? first : getNode(index - 1);

        pre.next = new Node<>(element, pre.next);

        size++;
    }

    /**
     * 获取索引所在的节点
     *
     * @param index
     * @return
     */
    private Node<E> getNode(int index) {
        rangeCheck(index);
        //从虚拟头节点开始找节点
        Node<E> node = first.next;
        for (int i = 0; i < index; i++) {
            node = node.next;
        }
        return node;
    }

    @Override
    public E remove(int index) {
        rangeCheck(index);
        Node<E> pre = index == 0 ? first : getNode(index - 1);
        Node<E> node = pre.next;
        pre.next = node.next;
        size--;
        return node.element;
    }

    @Override
    public int indexOf(E element) {
        if (element == null) {
            Node<E> node = first.next;
            for (int i = 0; i < size; i++) {
                if (node.element == null) return i;

                node = node.next;
            }
        } else {
            Node<E> node = first.next;
            for (int i = 0; i < size; i++) {
                // 因为element肯定不为null了,所以放在前面;避免空指针异常
                if (element.equals(node.element)) return i;

                node = node.next;
            }
        }
        return ELEMENT_NOT_FOUND;
    }


    @Override
    public String toString() {
        StringBuilder string = new StringBuilder();
        Node<E> node = first.next;
        string.append("size=").append(size).append(", [");
		for (int i = 0; i < size; i++) {
			if (i != 0) {
				string.append(", ");
			}

			string.append(node.element);

			node = node.next;
		}
		string.append("]");
        return string.toString();
    }
}
